<template>
  <view class="task-detail-page">
    <!-- 任务头部信息 -->
    <view class="task-header">
      <text class="task-title">{{ task.title }}</text>
      <view class="task-reward">
        <up-icon customPrefix="iconfont" name="jinbi" size="20" color="#ff9500"></up-icon>
        <up-text :text="task.points + ' 积分'" text-color="#ff9500" class="reward-points"></up-text>
      </view>
    </view>
    
    <!-- 任务基本信息卡片 -->
    <view class="info-card">
      <view class="info-item">
        <up-icon name="clock" size="18" color="#666666" />
        <text class="info-label">任务时间</text>
        <text class="info-value">{{ formatTaskTime(task.start_time, task.end_time) }}</text>
      </view>
      
      <view class="info-item">
        <u-icon customPrefix="iconfont" name="niming" size="18" color="#666666" />
        <text class="info-label">参与人数</text>
        <up-text class="info-value" :text="task.max_participants + '人参与'"></up-text>
      </view>
      
      <view class="info-item">
        <u-icon name="calendar" size="18" color="#666666" />
        <text class="info-label">有效期</text>
        <text class="info-value">{{ formatDateRange(task.valid_from, task.valid_to) }}</text>
      </view>
    </view>
    
    <!-- 任务描述 -->
    <view class="task-section">
      <view class="section-title">
        <text>任务描述</text>
      </view>
      <view class="task-description" v-html="formatRichText(task.description)"></view>
    </view>
   
    <!-- 任务要求 -->
    <view class="task-section">
      <view class="section-title">
        <text>任务要求（参考如下截图）</text>
      </view>
      <view class="task-requirements">
        <view class="requirement-item" v-for="(req, index) in taskRequirements" :key="index">
          <up-icon name="arrow-right" size="16" color="#409eff" />
          <text class="requirement-text">{{ req }}</text>
        </view>
      </view>
      <!-- Banner轮播图 -->
      <view style="margin: 20rpx 10rpx;" v-if="teachingImgs.length > 0">
        <up-swiper 
          :list="teachingImgs" 
          mode="dot" 
          height="300rpx"
          previousMargin="30"
          nextMargin="30"
          :indicator="true"
          indicatorActiveColor="blue"
          :acceleration="true"
          :circular="true"
          indicator-dots 
          autoplay 
          interval="5000"
          duration="500"
          @click="handleTeachingImgsClick"
        ></up-swiper>
      </view>
    </view>
    
    <!-- 常见问题 -->
    <view class="task-section" v-if="task.faq && task.faq.length > 0">
      <view class="section-title">
        <text>常见问题</text>
      </view>
      <u-collapse v-model="activeNames">
        <u-collapse-item 
          v-for="(item, index) in task.faq" 
          :key="index"
          :title="item.question"
          :name="`faq-${index}`"
        >
          <text class="faq-answer">{{ item.answer }}</text>
        </u-collapse-item>
      </u-collapse>
    </view>
    
    <!-- 底部操作栏 -->
    <view class="bottom-action">
      
      <view class="action-buttons">
        <up-button 
          type="default" 
          size="large"
          :plain="true"
          @click="navigateToSubmit"
        >
          <up-icon customPrefix="iconfont" name="shangchuan" size="20" color="#409eff" />
          <up-text text="提交任务" text-color="#409eff"></up-text>
        </up-button>
        
        <up-button 
          type="primary" 
          size="large"
          @click="handleClaimTask"
          :loading="claiming"
          :disabled="claiming"
        >
          <up-icon customPrefix="iconfont" name="lingqu" size="20" color="#fff" />
          <up-text :text="claiming ? '领取中...' : '领取素材'" ></up-text>
        </up-button>
      </view>
    </view>
    
    <!-- 登录弹窗 -->
    <login-modal 
      v-model:visible="showLoginModal" 
      @loginSuccess="handleLoginSuccess"
    ></login-modal>
    
    <!-- 提示弹窗 -->
    <u-toast ref="taskToast" />
    
    <!-- 加载中 -->
    <u-loading-page v-if="loading" color="#409eff"></u-loading-page>
  </view>
</template>

<script>
import { defineComponent, ref, computed, onMounted, reactive, watch } from 'vue';
import { useTaskStore } from '../../store/task.js';
import { useUserStore } from '../../store/user.js';
import { formatTime, formatPoints, getTaskStatusText } from '../../utils/common.js';
import taskMock from '../../api/taskMock.js';
import LoginModal from '../../components/login-modal.vue';

export default defineComponent({
  name: 'TaskDetail',
  components: {
    LoginModal
  },
  setup() {
    const taskStore = useTaskStore();
    const userStore = useUserStore();
    
    // 状态管理
    const loading = ref(true);
    const claiming = ref(false);
    const activeNames = ref([]);
    const showLoginModal = ref(false);
    const taskId = ref('');
    
    // 获取任务详情
    const task = computed(() => taskStore.currentTask);

    const handleTeachingImgsClick = (index) => {
      const img = teachingImgs.value[index];
      console.log("点击教学图片 ",index,": ",img);
      if (img.type === 1) {
        uni.navigateTo({
          url: img.link
        });
      }
    };

    // 教学图片数据
    const teachingImgs = ref([
      { 
        id: 1,
        type: 1,
        url: 'https://s3.bmp.ovh/imgs/2025/03/21/e93e41222d7c96b1.png',
        link: '', 
        title: '教程1'
      },
      { 
        id: 2,
        type: 1,
        url: 'https://s3.bmp.ovh/imgs/2025/03/21/d8f6a5f813e58a7b.png',
        link: '/pages/video/check-video', 
        title: '新手任务'
      },
      { 
        id: 3,
        type: 1,
        url: 'https://s3.bmp.ovh/imgs/2025/03/21/e93e41222d7c96b1.png',
        link: '/pages/video/check-video', 
        title: '每日签到'
      },
      { 
        id: 4,
        type: 1,
        url: 'https://s3.bmp.ovh/imgs/2025/03/29/89d03258b86b8079.jpg',
        link: '/pages/video/check-video', 
        title: '积分兑换'
      }
    ]);
    
    // 任务状态文本
    const taskStatusText = computed(() => {
      const statusMap = {
        'pending': '待开始',
        'in_progress': '进行中',
        'completed': '已完成',
        'expired': '已过期'
      };
      return statusMap[task.value.status] || '未知状态';
    });
    
    // 状态标签类型
    const statusTagType = computed(() => {
      const typeMap = {
        'pending': 'warning',
        'in_progress': 'primary',
        'completed': 'success',
        'expired': 'default'
      };
      return typeMap[task.value.status] || 'default';
    });
    
    // 任务要求列表
    const taskRequirements = computed(() => {
      // 如果任务有自定义要求，使用自定义要求
      if (task.value.requirements && task.value.requirements.length > 0) {
        return task.value.requirements;
      }
      
      // 默认要求
      return [
        '请按照任务要求完成操作',
        '提交内容必须真实有效',
        '禁止作弊行为，一经发现取消奖励',
        '每个任务仅限完成一次'
      ];
    });
    
    // 是否显示奖励信息
    const showRewardInfo = computed(() => {
      return task.value.status !== 'completed' && task.value.status !== 'expired';
    });
    
    // 是否显示提交按钮
    const showSubmitButton = computed(() => {
      return userStore.isLoggedIn && task.value.is_claimed && !task.value.is_submitted && task.value.status !== 'expired';
    });
    
    // 是否显示已完成按钮
    const showCompletedButton = computed(() => {
      return task.value.is_submitted && task.value.status !== 'expired';
    });
    
    // 是否显示已过期按钮
    const showExpiredButton = computed(() => {
      return task.value.status === 'expired';
    });
    
    // 加载任务详情
    const loadTaskDetail = async (id) => {
      if (!id) return;
      
      try {
        loading.value = true;
        
        // 模拟网络延迟
        await new Promise(resolve => setTimeout(resolve, 300));
        
        // 从taskMock数据源中查找任务
        const task = taskMock.mockTasks.find(t => t.id === id);
        
        if (task) {
          // 更新taskStore中的当前任务
          taskStore.setCurrentTask(task);
        } else {
          console.error('未找到任务:', id);
          uni.showToast({
            title: '未找到任务',
            icon: 'none'
          });
        }
      } catch (error) {
        console.error('加载任务详情失败:', error);
        uni.showToast({
          title: '加载失败，请稍后重试',
          icon: 'none'
        });
      } finally {
        loading.value = false;
      }
    };
    
    // 格式化任务时间
    const formatTaskTime = (startTime, endTime) => {
      if (!startTime) return '暂无时间限制';
      
      const start = formatTime(startTime, 'YYYY-MM-DD');
      const end = endTime ? ` - ${formatTime(endTime, 'YYYY-MM-DD')}` : ' 起';
      return start + end;
    };
    
    // 格式化富文本内容（简单实现）
    const formatRichText = (richText) => {
      if (!richText) return '';
      return richText;
    };
    
    // 格式化日期范围
    const formatDateRange = (startDate, endDate) => {
      if (!startDate) return '暂无时间限制';
      
      const start = formatTime(startDate, 'YYYY-MM-DD');
      const end = endDate ? ` - ${formatTime(endDate, 'YYYY-MM-DD')}` : ' 起';
      return start + end;
    };
    
    // 返回上一页
    const handleBack = () => {
      uni.navigateBack();
    };
    
    // 处理任务领取
    const handleClaimTask = async () => {
      try {
        claiming.value = true;
        const result = await taskStore.claimTask(taskId.value);
        
        if (result && result.success) {
          uni.showToast({
            title: '领取成功',
            icon: 'success'
          });
          // 重新加载任务详情
          await loadTaskDetail(taskId.value);
        } else {
          uni.showToast({
            title: result.message || '领取失败',
            icon: 'none'
          });
        }
      } catch (error) {
        uni.showToast({
          title: '领取失败，请稍后重试',
          icon: 'none'
        });
      } finally {
        claiming.value = false;
      }
    };
    
    // 导航到任务提交页面
    const navigateToSubmit = () => {
      uni.navigateTo({
        url: `/pages/task-submit/task-submit?id=${taskId.value}`
      });
    };
    
    // 处理分享
    const handleShare = () => {
      // 检查登录状态
      if (!userStore.isLoggedIn) {
        showLoginModal.value = true;
        return;
      }
      
      // 调用分享功能
      uni.showShareMenu({
        withShareTicket: true,
        menus: ['shareAppMessage', 'shareTimeline']
      });
    };
    
    // 处理登录成功
    const handleLoginSuccess = () => {
      showLoginModal.value = false;
      // 重新加载任务详情，显示用户相关状态
      loadTaskDetail(taskId.value);
    };
    
    // 生命周期
    onMounted(() => {
      // 获取任务ID
      const pages = getCurrentPages();
      const currentPage = pages[pages.length - 1];
      taskId.value = currentPage.options.id || '';
      
      // 加载任务详情
      if (taskId.value) {
        loadTaskDetail(taskId.value);
      } else {
        loading.value = false;
        uni.showToast({
          title: '任务ID不存在',
          icon: 'none'
        });
      }
    });
    
    return {
      loading,
      claiming,
      activeNames,
      showLoginModal,
      task,
      teachingImgs,
      handleTeachingImgsClick,
      taskStatusText,
      statusTagType,
      taskRequirements,
      showRewardInfo,
      showSubmitButton,
      showCompletedButton,
      showExpiredButton,
      formatTaskTime,
      formatDateRange,
      formatRichText,
      handleBack,
      handleClaimTask,
      navigateToSubmit,
      handleShare,
      handleLoginSuccess
    };
  }
});
</script>

<style lang="scss" scoped>
.task-detail-page {
  padding: 16px;
  min-height: 100vh;
  background-color: #f5f5f5;
  padding-bottom: 100px; // 为底部操作栏留出空间
}

.task-header {
  background-color: #ffffff;
  border-radius: 12px;
  padding: 20px;
  margin-bottom: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  position: relative;
  padding-top: 44px; // 为fixed按钮留出空间
  
  .task-title {
    display: block;
    font-size: 20px;
    font-weight: 700;
    color: #333333;
    margin-bottom: 12px;
    line-height: 1.4;
  }
  
  .task-reward {
    display: flex;
    align-items: center;
    
    .reward-points {
      font-size: 18px;
      font-weight: 600;
      color: #ff9500;
      margin-left: 6px;
    }
  }
}

.info-card {
  background-color: #ffffff;
  border-radius: 12px;
  padding: 16px;
  margin-bottom: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  
  .info-item {
    display: flex;
    align-items: center;
    margin-bottom: 12px;
    .info-label {
      margin: 1px 10px;
    }
    &:last-child {
      margin-bottom: 0;
    }
  
  }
}

.task-section {
  background-color: #ffffff;
  border-radius: 12px;
  padding: 16px;
  margin-bottom: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  
  .section-title {
    margin-bottom: 12px;
    
    text {
      font-size: 16px;
      font-weight: 600;
      color: #333333;
      position: relative;
      padding-left: 12px;
      
      &::before {
        content: '';
        position: absolute;
        left: 0;
        top: 50%;
        transform: translateY(-50%);
        width: 4px;
        height: 16px;
        background-color: #409eff;
        border-radius: 2px;
      }
    }
  }
  
  .task-description {
    font-size: 14px;
    color: #666666;
    line-height: 1.6;
    
    // 富文本内容样式
    :deep() {
      img {
        max-width: 100%;
        height: auto;
        margin: 8px 0;
      }
      
      p {
        margin-bottom: 8px;
      }
      
      a {
        color: #409eff;
        text-decoration: none;
      }
    }
  }
  
  .task-requirements {
    .requirement-item {
      display: flex;
      align-items: flex-start;
      margin-bottom: 8px;
      
      &:last-child {
        margin-bottom: 0;
      }
      
      .requirement-text {
        flex: 1;
        font-size: 14px;
        color: #666666;
        line-height: 1.5;
        margin-left: 8px;
      }
    }
  }
  
  .faq-answer {
    font-size: 14px;
    color: #666666;
    line-height: 1.5;
  }
}

.bottom-action {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #ffffff;
  padding: 16px;
  box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.08);
  z-index: 9;
  
  .action-buttons {
    display: flex;
    gap: 12px;
    
    :deep() {
      .u-button {
        flex: 1;
        height: 44px;
        font-size: 16px;
        
        .u-icon {
          margin-right: 4px;
        }
      }
    }
  }
}

</style>